<template>
   <div class="answer-page" v-if="curTopic && curTopic.topic">
    <div class="problem">
      <span class="title">{{ order + 1 }}. {{ curTopic.topic }}</span>
      <span class="type">( {{ curTopic.topicType }} )</span>
    </div>
    <div class="answer-list">
      <van-checkbox-group v-model="checkboxResult">
        <van-cell-group>
          <van-cell v-for="(item, index) of curTopic.optionList" clickable :key="index" :title="`${ item.name }. ${ item.content }`"
            @click="toggle(item, index)">
            <template #right-icon>
              <van-checkbox :name="item.name" ref="checkboxes" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </div>
    <div class="button-group">
<!--      <div class="btn prev-btn" @click="handleCC('success')">成功</div>-->
<!--      <div class="btn next-btn" @click="handleCC('error')">失败</div>-->
      <div class="btn prev-btn" v-show="isShowBtn.prev" @click="handlePrevProblem">上一题</div>
      <div class="btn next-btn" v-show="isShowBtn.next" @click="handleNextProblem">下一题</div>
      <div class="btn submit-btn" v-show="isShowBtn.submit" @click="handleSubmit">提交</div>
    </div>
  </div>
</template>

<script setup>
import {useAnswerList, useCurrentVideo,} from '@/store/answer.js';
import { onMounted, ref } from 'vue';
import { onBeforeRouteUpdate, useRouter, useRoute } from "vue-router";
import  { postAnswer, scoreToRecord } from '@/api/answer.js';

const parentId = JSON.parse(localStorage.getItem('parentId'));
const route = useRoute();
const router = useRouter();
const { answerList, answerListLength, setAnswerList, modifyAnswerList } = useAnswerList();
const curTopic = ref(null);
const checkboxResult = ref([]);
const radioResult = ref('');

//  第几题 从 0开始
const order = ref(0);
const topicType = ref('单选题');

//  控制按钮的显示
const isShowBtn = ref({
  prev: false,
  next: false,
  submit: false
})

onMounted(() => {
  loadingData(route.query.order);
  //  判断按钮的显示情况
  btnDisplay( order.value );
})

//  只改变参数，触发该事件
onBeforeRouteUpdate((to, from) => {
  loadingData(to.query.order);
  //  判断按钮的显示情况
  btnDisplay( order.value );
})

//  处理按钮的显示和隐藏
const btnDisplay = (val) => {
  if(answerListLength === 1) {  // 只有一道题
    isShowBtn.value = {
      prev: false,
      next: false,
      submit: true
    }
  } else if( val === answerListLength - 1 ) {  //  是否满足提交
    isShowBtn.value = {
      prev: true,
      next: false,
      submit: true
    }
  } else if(val === 0) {  //  是否是第一题
    isShowBtn.value = {
      prev: false,
      next: true,
      submit: false
    }
  } else {  //  正常显示
    isShowBtn.value = {
      prev: true,
      next: true,

      submit: false
    }
  }
}

//  处理请求数据
const loadingData = (o) => {
  //  获取题目
  const timu = answerList[order.value];
  //  每次进入，需要清空上一次的 result 结果
  checkboxResult.value = timu.answerArray;
  radioResult.value = '';
  order.value = Number(o);
  curTopic.value = timu;
  topicType.value = curTopic.value.topicType;
}

//  上一题
const handlePrevProblem = () => {
  order.value--;
  //  只修改参数，页面并不会变化
  router.replace({ path: '/AnswerPage', query: { order: order.value } });
}

//  下一题
const handleNextProblem = () => {
  order.value++;
  //  只修改参数，页面并不会变化
  router.replace({ path: '/AnswerPage', query: { order: order.value } });
  //  需要判断当前有没有答题，如果没有答题提示用户是否需要向下进行
}

const { currentVideoId } = useCurrentVideo();
//  答完提交
const handleSubmit = async () => {
  const userAnswerList = answerList.reduce((prev, item, index) => {
    prev[index] = {
      "videoCardId": item.cardId,
      "answer": item.userAnswer
    }

    return prev;
  }, [])

  //  提交答案
  const { code, data } = await postAnswer({
    videoId: currentVideoId,
    answerList: userAnswerList,
    parentId
  });

  if(code === 200) { //  成功页面
      //  积分转换 - 积分转换完成 跳转到成功页面
      // await scoreToRecord({
      //   parentId: JSON.parse(localStorage.getItem('parentId')),
      //   changeId: data.videoCardRecordId,
      //   changeScore: Number(data.score),
      //   changeType: '02'
      // });

      router.replace({ path: '/AnswerResultSuccess', query: { score: data.score } });
  } else { // 跳转回失败页面
    router.replace({ path: '/AnswerResultError' });
  }
}


//  多选
const checkboxes = ref(null);
const toggle = (item, index) => {
  //  单选 直接清空数组
  if(topicType.value === '单选题' ) {  //  单选，带不选择的功能
    if(checkboxResult.value.includes(item.name)) {
      checkboxResult.value = [];
    } else {
      checkboxResult.value = [];
      checkboxes.value[index].toggle();
      checkboxResult.value = [item.name];
    }
  } else {  // 多选
    checkboxes.value[index].toggle();
  }
  //  每次切换 调用修改接口对数据进行修改
  modifyAnswerList(order.value, checkboxResult.value);
}
</script>

<style lang="scss" scoped>
.answer-page {
  background: #fff;
  height: 100%;
  padding: 0 1.4rem;
  box-sizing: border-box;

  .problem {
    padding: 1rem 0;
    font-size: 1.8rem;
  }

  .button-group {
    display: flex;
    justify-content: center;
    margin-top: 3rem;

    .btn {
      margin-right: 1rem;
      width: 10rem;
      height: 4rem;
      background: #38b9fa;
      border-radius: 2rem;
      font-size: 1.6rem;
      color: #fff;
      text-align: center;
      line-height: 4rem;
    }
  }
}
</style>